package vn.lumi.smarthome.provider;

import java.util.ArrayList;

import vn.lumi.smarthome.LumiHome;
import vn.lumi.smarthome.io.database.DatabaseHelper;
import vn.lumi.smarthome.io.database.TBL_Device;
import vn.lumi.smarthome.io.database.TBL_DeviceScene;
import vn.lumi.smarthome.io.database.TBL_DeviceState;
import vn.lumi.smarthome.io.database.TBL_Floor;
import vn.lumi.smarthome.io.database.TBL_Room;
import vn.lumi.smarthome.io.database.TBL_Scene;
import vn.lumi.smarthome.io.database.TBL_Schedule;
import vn.lumi.smarthome.io.model.Device;
import vn.lumi.smarthome.io.model.DeviceState;
import vn.lumi.smarthome.io.model.Floor;
import vn.lumi.smarthome.io.model.Room;
import vn.lumi.smarthome.io.model.Scene;
import vn.lumi.smarthome.io.model.Schedule;
import vn.lumi.smarthome.io.model.Time;
import vn.lumi.smarthome.network.CreateSchedule;
import vn.lumi.smarthome.network.DelSchedule;
import vn.lumi.smarthome.network.EditSchedule;
import vn.lumi.smarthome.network.ToggleSchedule;
import vn.lumi.smarthome.network.TurnOnScene;
import vn.lumi.smarthome.network.AppMsg;
import vn.lumi.smarthome.network.ControlNormalDevice;
import vn.lumi.smarthome.network.ControlRGB;
import vn.lumi.smarthome.network.CreateScene;
import vn.lumi.smarthome.network.DelScene;
import vn.lumi.smarthome.network.EditScene;
import vn.lumi.smarthome.network.NetMessage;
import vn.lumi.smarthome.service.SmartHomeService;
import vn.lumi.smarthome.ui.AbstractSceneActivity;
import vn.lumi.smarthome.ui.DeviceFragment;
import vn.lumi.smarthome.ui.EditSceneFragment;
import vn.lumi.smarthome.ulti.LogUltis;
import android.R.integer;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.Parcel;
import android.os.RemoteException;
import android.text.Selection;
import android.util.Log;

public class SmartHomeProvider extends ContentProvider implements
		ServiceConnection {
	private static final String TAG = "SmartHomeProvider";

	public static final String AUTHORITY = "vn.lumi.smarthome.provider.SmartHomeProvider";
	private static UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

	private static final int OPT_FLOOR = 1;
	private static final int OPT_ROOM = OPT_FLOOR + 1;
	private static final int OPT_DEVICES = OPT_ROOM + 1;
	private static final int OPT_DEVICE_STATE = OPT_DEVICES + 1;
	private static final int OPT_SCENE = OPT_DEVICE_STATE + 1;
	private static final int OPT_DEVICE_SCENE = OPT_SCENE + 1;
	private static final int OPT_SCHEDULE = OPT_DEVICE_SCENE + 1;
	private static final int OPT_DEVICE_TYPE = OPT_SCHEDULE + 1;
	private static final int OPT_BIND_SERVICE = OPT_DEVICE_TYPE + 1;
	private static final int OPT_CONTROL_NORMAL_DEVICE = OPT_BIND_SERVICE + 1;
	private static final int OPT_CONTROL_RGB = OPT_CONTROL_NORMAL_DEVICE + 1;
	private static final int OPT_END_APPLICATION = OPT_CONTROL_RGB + 1;
	private static final int OPT_DEVICE_STATE_ID = OPT_END_APPLICATION + 1;
	private static final int OPT_SCENE_CREATE_SCENE = OPT_DEVICE_STATE_ID + 1;
	private static final int OPT_SCENE_TURNON_SCENE = OPT_SCENE_CREATE_SCENE + 1;
	private static final int OPT_SCENE_TURNOFF_SCENE = OPT_SCENE_TURNON_SCENE + 1;
	private static final int OPT_SCENE_EDIT_SCENE = OPT_SCENE_TURNOFF_SCENE + 1;
	private static final int OPT_SCENE_DELETE_SCENE = OPT_SCENE_EDIT_SCENE + 1;
	private static final int OPT_SCHEDULE_TURN_ON = OPT_SCENE_DELETE_SCENE + 1;
	private static final int OPT_SCHEDULE_TURN_OFF = OPT_SCHEDULE_TURN_ON + 1;
	private static final int OPT_SCHEDULE_ADD = OPT_SCHEDULE_TURN_OFF + 1;
	private static final int OPT_SCHEDULE_EDIT = OPT_SCHEDULE_ADD + 1;
	private static final int OPT_SCHEDULE_DELETE = OPT_SCHEDULE_EDIT + 1;
	private static final int OPT_SCHEDULE_DEVICE = OPT_SCHEDULE_DELETE + 1;

	public static final Uri BIND_SERVICE_URI = Uri.parse("content://"
			+ SmartHomeProvider.AUTHORITY + "/" + "BIND_SERVICE");

	public static final Uri END_APPLICATION_URI = Uri.parse("content://"
			+ SmartHomeProvider.AUTHORITY + "/" + "END_APPLICATION");

	private ServiceConnection mConnection = (ServiceConnection) this;
	private final Messenger mMessenger = new Messenger(
			new IncomingMessageHandler());
	private Messenger mServiceMessenger = null;
	boolean mIsBound;
	LumiHome myApp;

	static {
		sUriMatcher.addURI(AUTHORITY, TBL_Floor.FLOOR, OPT_FLOOR);
		sUriMatcher.addURI(AUTHORITY, TBL_Room.ROOM, OPT_ROOM);
		sUriMatcher.addURI(AUTHORITY, TBL_Device.DEVICES, OPT_DEVICES);
		sUriMatcher.addURI(AUTHORITY, TBL_Device.DEVICES + "/*",
				OPT_DEVICE_STATE);
		sUriMatcher.addURI(AUTHORITY, TBL_Device.DEVICE_TYPE, OPT_DEVICE_TYPE);
		sUriMatcher.addURI(AUTHORITY, TBL_Scene.SCENE, OPT_SCENE);
		sUriMatcher.addURI(AUTHORITY, TBL_DeviceScene.DEVICE_SCENE,
				OPT_DEVICE_SCENE);
		sUriMatcher.addURI(AUTHORITY, TBL_Schedule.SCHEDULE, OPT_SCHEDULE);
		sUriMatcher.addURI(AUTHORITY, "BIND_SERVICE", OPT_BIND_SERVICE);
		sUriMatcher.addURI(AUTHORITY, "END_APPLICATION", OPT_END_APPLICATION);
		sUriMatcher.addURI(AUTHORITY, TBL_Device.CONTROL_NORMAL_DEVICE,
				OPT_CONTROL_NORMAL_DEVICE);
		sUriMatcher.addURI(AUTHORITY, TBL_Device.CONTROL_RGB, OPT_CONTROL_RGB);
		sUriMatcher.addURI(AUTHORITY, TBL_Device.DEVICE_STATE_ID,
				OPT_DEVICE_STATE_ID);
		sUriMatcher.addURI(AUTHORITY, TBL_Scene.CREATE_SCENE,
				OPT_SCENE_CREATE_SCENE);
		sUriMatcher.addURI(AUTHORITY, TBL_Scene.EDIT_SCENE,
				OPT_SCENE_EDIT_SCENE);
		sUriMatcher.addURI(AUTHORITY, TBL_Scene.TURNON_SCENE,
				OPT_SCENE_TURNON_SCENE);
		sUriMatcher.addURI(AUTHORITY, TBL_Scene.TURNOFF_SCENE,
				OPT_SCENE_TURNOFF_SCENE);
		sUriMatcher.addURI(AUTHORITY, TBL_Scene.DELETE_SCENE,
				OPT_SCENE_DELETE_SCENE);
		sUriMatcher.addURI(AUTHORITY, TBL_Schedule.SCHEDULE_DEVICE,
				OPT_SCHEDULE_DEVICE);
		// Author : Hieu
		sUriMatcher.addURI(AUTHORITY, TBL_Schedule.SCHEDULE_TURN_ON,
				OPT_SCHEDULE_TURN_ON);
		sUriMatcher.addURI(AUTHORITY, TBL_Schedule.SCHEDULE_TURN_OFF,
				OPT_SCHEDULE_TURN_OFF);
		sUriMatcher.addURI(AUTHORITY, TBL_Schedule.SCHEDULE_EDIT,
				OPT_SCHEDULE_EDIT);
		sUriMatcher.addURI(AUTHORITY, TBL_Schedule.SCHEDULE_DELETE,
				OPT_SCHEDULE_DELETE);
		sUriMatcher.addURI(AUTHORITY, TBL_Schedule.SCHEDULE_ADD,
				OPT_SCHEDULE_ADD);

	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {

		SQLiteDatabase database = DatabaseHelper.getInstance(getContext())
				.getWritableDatabase();
		int match = sUriMatcher.match(uri);
		String tableName = "";
		switch (match) {
		case OPT_FLOOR:
			tableName = DatabaseHelper.DB_TBL_FLOOR;
			break;
		case OPT_ROOM:
			tableName = DatabaseHelper.DB_TBL_ROOM;
			break;
		case OPT_DEVICES:
			tableName = DatabaseHelper.DB_TBL_DEVICE;
			break;
		case OPT_SCENE:
			tableName = DatabaseHelper.DB_TBL_SCENE;
			break;
		case OPT_DEVICE_STATE:
			tableName = DatabaseHelper.DB_TBL_DEVICE_STATE;
			break;
		case OPT_DEVICE_SCENE:
			tableName = DatabaseHelper.DB_TBL_DEVICE_SCENE;
			break;
		case OPT_SCHEDULE:
			tableName = DatabaseHelper.DB_TBL_SCHEDULE;
			break;
		case OPT_BIND_SERVICE:
			doBindService();
			return 0;
		default:
			break;
		}
		int rows = database.delete(tableName, selection, selectionArgs);
		getContext().getContentResolver().notifyChange(uri, null);
		return rows;

	}

	@Override
	public String getType(Uri uri) {

		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		SQLiteDatabase database = DatabaseHelper.getInstance(getContext())
				.getWritableDatabase();
		long row = -1;
		int match = sUriMatcher.match(uri);
		switch (match) {
		case OPT_FLOOR:
			row = database.insert(DatabaseHelper.DB_TBL_FLOOR, null, values);
			break;
		case OPT_ROOM:
			row = database.insert(DatabaseHelper.DB_TBL_ROOM, null, values);
			break;
		case OPT_DEVICES:
			row = database.insert(DatabaseHelper.DB_TBL_DEVICE, null, values);
			break;
		case OPT_SCENE:
			row = database.insert(DatabaseHelper.DB_TBL_SCENE, null, values);
			break;
		case OPT_DEVICE_STATE:
			row = database.insert(DatabaseHelper.DB_TBL_DEVICE_STATE, null,
					values);
			break;
		case OPT_DEVICE_SCENE:
			row = database.insert(DatabaseHelper.DB_TBL_DEVICE_SCENE, null,
					values);
			break;
		case OPT_SCHEDULE:
			Log.e("ban tin", "OPT_SCHEDULE");
			row = database.insert(DatabaseHelper.DB_TBL_SCHEDULE, null, values);
			break;
		default:
			break;
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return Uri.withAppendedPath(uri, row + "");
	}

	@Override
	public boolean onCreate() {
		Log.d("CP", "onCreate");
		return false;
	}

	public void doBindService() {
		if (SmartHomeService.isRunning()) {
			getContext().bindService(
					new Intent(getContext(), SmartHomeService.class),
					mConnection, Context.BIND_AUTO_CREATE);
			mIsBound = true;
			Log.d("Content Provider", "Binding service");
		} else
			Log.d("Content Provider", "Service is not running");
	}

	@SuppressLint("NewApi")
	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		int match = sUriMatcher.match(uri);
		SQLiteDatabase sqLiteDatabase = DatabaseHelper
				.getInstance(getContext()).getWritableDatabase();
		Cursor cursor = null;
		switch (match) {
		case OPT_DEVICE_STATE_ID:
			LogUltis.i(TAG, "Query Device table");
			cursor = sqLiteDatabase
					.query(DatabaseHelper.DB_TBL_DEVICE, projection, selection,
							selectionArgs, null, sortOrder, null);
			break;
		case OPT_DEVICE_TYPE:
			LogUltis.i(TAG, "Query Device table");
			cursor = sqLiteDatabase
					.query(DatabaseHelper.DB_TBL_DEVICE, projection, selection,
							selectionArgs, null, sortOrder, null);
			break;
		case OPT_FLOOR:
			LogUltis.i(TAG, "Query floor table");
			cursor = sqLiteDatabase
					.query(DatabaseHelper.DB_TBL_FLOOR, projection, selection,
							selectionArgs, null, sortOrder, null);
			break;
		case OPT_ROOM:
			LogUltis.i(TAG, "Query room table");
			cursor = sqLiteDatabase
					.query(DatabaseHelper.DB_TBL_ROOM, projection, selection,
							selectionArgs, null, null, sortOrder);
			break;
		case OPT_DEVICES:
			String device_id = DatabaseHelper.DB_TBL_DEVICE + "."
					+ TBL_Device._ID;
			String device_type = DatabaseHelper.DB_TBL_DEVICE + "."
					+ TBL_Device.TYPE_ID;
			String room_id = DatabaseHelper.DB_TBL_DEVICE + "."
					+ TBL_Device.ROOM_ID;
			String device_name = DatabaseHelper.DB_TBL_DEVICE + "."
					+ TBL_Device.NAME;
			String device_stateid = DatabaseHelper.DB_TBL_DEVICE + "."
					+ TBL_Device.STATE_ID;
			String is_control = DatabaseHelper.DB_TBL_DEVICE + "."
					+ TBL_Device.IS_CONTROL;

			String state_id = DatabaseHelper.DB_TBL_DEVICE_STATE + "."
					+ TBL_DeviceState._ID;
			String value = DatabaseHelper.DB_TBL_DEVICE_STATE + "."
					+ TBL_DeviceState.VALUE;
			String RGB = DatabaseHelper.DB_TBL_DEVICE_STATE + "."
					+ TBL_DeviceState.RGB;
			String Schedule_device_id = DatabaseHelper.DB_TBL_SCHEDULE + "."
					+ TBL_Schedule.DEVICE_ID;
			String Schedule_state = DatabaseHelper.DB_TBL_SCHEDULE + "."
					+ TBL_Schedule.STATE;


			// Hieuph: modify
			String[] projections = new String[] { device_id, device_type,
					room_id, device_name, device_stateid, is_control, value,
					RGB, Schedule_device_id, "MAX(" + Schedule_state + ")" + " AS" + " max_schedule_state"};

			String stringInner = DatabaseHelper.DB_TBL_DEVICE + " INNER JOIN "
					+ DatabaseHelper.DB_TBL_DEVICE_STATE + " ON ("
					+ device_stateid + "=" + state_id + ")" + " LEFT JOIN "
					+ DatabaseHelper.DB_TBL_SCHEDULE + " ON (" + device_id
					+ "=" + Schedule_device_id + " )";

			SQLiteQueryBuilder sqLiteQueryBuilder = new SQLiteQueryBuilder();
			sqLiteQueryBuilder.setTables(stringInner);

			// Hieuph modify
			if (Build.VERSION.SDK_INT < 11) {
				@SuppressWarnings("deprecation")
				String query = sqLiteQueryBuilder.buildQuery(projections,
						selection, selectionArgs, device_id, null, sortOrder, null);
				LogUltis.i(TAG, "SQL get devices (API<11)=[" + query + "]");
				cursor = sqLiteDatabase.rawQuery(query, selectionArgs);
			} else {
				String query = sqLiteQueryBuilder.buildQuery(projections,
						selection, device_id, null, sortOrder, null);
				LogUltis.i(TAG, "SQL get devices (API>=11)=[" + query + "]");
				cursor = sqLiteDatabase.rawQuery(query, selectionArgs);
			}
			break;
		case OPT_SCHEDULE_DEVICE:
			LogUltis.i(TAG, "Query device Schedule");

			String[] pros1 = new String[] {
					DatabaseHelper.DB_TBL_SCHEDULE + "." + TBL_Schedule._ID
							+ " AS " + TBL_Schedule._ID,
					TBL_Schedule.DEVICE_ID,
					TBL_Schedule.STATE,
					TBL_Schedule.REPEAT,
					TBL_Schedule.MONDAY,
					TBL_Schedule.TUESDAY,
					TBL_Schedule.WEDNESDAY,
					TBL_Schedule.THURSDAY,
					TBL_Schedule.FRIDAY,
					TBL_Schedule.SATURDAY,
					TBL_Schedule.SUNDAY,
					TBL_Schedule.HOUR,
					TBL_Schedule.MINUTE,
					// TBL_Schedule.DURATION,
					TBL_Schedule.HOUR_END,
					TBL_Schedule.MINUTE_END,
					DatabaseHelper.DB_TBL_SCHEDULE + "."
							+ TBL_Schedule.STATE_ID, TBL_DeviceState.VALUE,
					TBL_DeviceState.BLIND_STATE, TBL_DeviceState.RGB };

			String inner1 = DatabaseHelper.DB_TBL_SCHEDULE + " INNER JOIN "
					+ DatabaseHelper.DB_TBL_DEVICE_STATE + " ON ("
					+ DatabaseHelper.DB_TBL_SCHEDULE + "."
					+ TBL_Schedule.STATE_ID + "="
					+ DatabaseHelper.DB_TBL_DEVICE_STATE + "."
					+ TBL_DeviceState._ID + ") ";

			SQLiteQueryBuilder builder1 = new SQLiteQueryBuilder();
			builder1.setTables(inner1);
			String a = DatabaseHelper.DB_TBL_SCHEDULE + "." + selection;

			if (Build.VERSION.SDK_INT < 11) {
				@SuppressWarnings("deprecation")
				String query = builder1.buildQuery(pros1, selection,
						selectionArgs, null, null, sortOrder, null);
				LogUltis.i(TAG, "SQL get device_schedule (API<11)=[" + query
						+ "]");
				cursor = sqLiteDatabase.rawQuery(query, selectionArgs);
			} else {
				String query = builder1.buildQuery(pros1, a, null, null,
						sortOrder, null);
				LogUltis.i(TAG, "SQL get device_schedule (API>=11)=[" + query
						+ "]");
				cursor = sqLiteDatabase.rawQuery(query, selectionArgs);

			}

			break;
		case OPT_DEVICE_SCENE:
			LogUltis.i(TAG, "Query device Scene");
			String[] pros = new String[] {
					DatabaseHelper.DB_TBL_DEVICE_SCENE + "."
							+ TBL_DeviceScene._ID + " AS "
							+ TBL_DeviceScene._ID,
					TBL_DeviceScene.SCENE_ID,
					TBL_DeviceScene.DEVICE_ID,
					DatabaseHelper.DB_TBL_DEVICE_SCENE + "."
							+ TBL_DeviceScene.STATE_ID, TBL_DeviceState.VALUE,
					TBL_DeviceState.BLIND_STATE, TBL_DeviceState.RGB,
					TBL_Device.TYPE_ID };
			String inner = DatabaseHelper.DB_TBL_DEVICE_SCENE + " INNER JOIN "
					+ DatabaseHelper.DB_TBL_DEVICE_STATE + " ON ("
					+ DatabaseHelper.DB_TBL_DEVICE_SCENE + "."
					+ TBL_DeviceScene.STATE_ID + "="
					+ DatabaseHelper.DB_TBL_DEVICE_STATE + "."
					+ TBL_DeviceState._ID + ") "

					+ " INNER JOIN " + DatabaseHelper.DB_TBL_DEVICE + " ON ("
					+ TBL_DeviceScene.DEVICE_ID + "="
					+ DatabaseHelper.DB_TBL_DEVICE + "." + TBL_Device._ID + ")";

			SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
			builder.setTables(inner);

			if (Build.VERSION.SDK_INT < 11) {
				@SuppressWarnings("deprecation")
				String query = builder.buildQuery(pros, selection,
						selectionArgs, null, null, sortOrder, null);
				LogUltis.i(TAG, "SQL get device_scene (API<11)=[" + query + "]");
				cursor = sqLiteDatabase.rawQuery(query, selectionArgs);
			} else {
				String query = builder.buildQuery(pros, selection, null, null,
						sortOrder, null);
				LogUltis.i(TAG, "SQL get device_scene (API>=11)=[" + query
						+ "]");
				cursor = sqLiteDatabase.rawQuery(query, selectionArgs);
			}

			break;
		case OPT_SCENE:
			cursor = sqLiteDatabase.query(DatabaseHelper.DB_TBL_SCENE,
					projection, selection, selectionArgs, null, null, null);
			break;
		case OPT_SCHEDULE:
			cursor = sqLiteDatabase.query(DatabaseHelper.DB_TBL_SCHEDULE,
					projection, selection, selectionArgs, null, null, null);
			break;
		default:
			break;
		}
		if (cursor != null) {
			LogUltis.i(TAG, "cursor ! null, num rows=" + cursor.getCount());
			cursor.setNotificationUri(getContext().getContentResolver(), uri);
		}
		return cursor;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		SQLiteDatabase sqLiteDatabase = DatabaseHelper
				.getInstance(getContext()).getWritableDatabase();
		int match = sUriMatcher.match(uri);
		int effect = 0;
		switch (match) {
		case OPT_DEVICES:
			effect = sqLiteDatabase.update(DatabaseHelper.DB_TBL_DEVICE,
					values, selection, selectionArgs);
			Log.e("ban tin", "update device");
			break;
		case OPT_DEVICE_STATE:
			Log.e("ban tin", "update device_state");
			effect = sqLiteDatabase.update(DatabaseHelper.DB_TBL_DEVICE_STATE,
					values, selection, selectionArgs);
			break;
		case OPT_SCENE:
			LogUltis.i(TAG, "update scene");
			effect = sqLiteDatabase.update(DatabaseHelper.DB_TBL_SCENE, values,
					selection, selectionArgs);
			break;
		case OPT_CONTROL_NORMAL_DEVICE:
			int[] deviceID = DeviceFragment.convertStringToIntArray(values
					.getAsString("DeviceID"));
			int[] stateValue = DeviceFragment.convertStringToIntArray(values
					.getAsString("DeviceStateValue"));
			int[] stateID = DeviceFragment.convertStringToIntArray(values
					.getAsString("StateID"));
			if (deviceID == null)
				return 0;
			int NumOfDevice = deviceID.length;
			// update isControl
			for (int i = 0; i < NumOfDevice; i++) {

				ContentValues values1 = new ContentValues();
				values1.put(TBL_Device.IS_CONTROL,
						Device.DEVICE_STATE_CONTROL_YES);
				String selection1 = TBL_Device._ID + "=?";
				String[] selectionArgs1 = new String[] { String
						.valueOf(deviceID[i]) };
				sqLiteDatabase.update(DatabaseHelper.DB_TBL_DEVICE, values1, // bo
																				// dong
																				// nay
						selection1, selectionArgs1);
				// if is dimmer --> update device state
				int deviceType = getType_id(getContext(), deviceID[i]);
				if (deviceType == Device.DEVICE_TYPE_DIMMER
						|| deviceType == Device.DEVICE_TYPE_FAN) {
					values1.clear();
					values1.put(TBL_DeviceState.VALUE, stateValue[i]);
					selection1 = TBL_DeviceState.ID + "=?";
					selectionArgs1 = new String[] { String.valueOf(stateID[i]) };
					sqLiteDatabase.update(DatabaseHelper.DB_TBL_DEVICE_STATE,
							values1, selection1, selectionArgs1);
				}
			}

			// format message
			ControlNormalDevice control = new ControlNormalDevice(0,
					LumiHome.Uid, LumiHome.Session_id, deviceID, stateValue,
					stateID);

			// send msg to Service
			sendMessageToService(NetMessage.CMD_APP_CONTROL_NORMAL, control);
			break;
		case OPT_CONTROL_RGB:
			int[] rgbID = DeviceFragment.convertStringToIntArray(values
					.getAsString("DeviceID"));
			int[] colorValue = DeviceFragment.convertStringToIntArray(values
					.getAsString("DeviceStateValue"));
			int[] rgbStateID = DeviceFragment.convertStringToIntArray(values
					.getAsString("StateID"));
			int[] rgbValue = new int[colorValue.length * 3];
			if (rgbID == null)
				return 0;
			int NumOfRGB = rgbID.length;
			// update isControl
			for (int i = 0; i < NumOfRGB; i++) {
				ContentValues values1 = new ContentValues();
				values1.put(TBL_Device.IS_CONTROL,
						Device.DEVICE_STATE_CONTROL_YES);
				String selection1 = TBL_Device._ID + "=?";
				String[] selectionArgs1 = new String[] { String
						.valueOf(rgbID[i]) };
				getContext().getContentResolver().update(
						TBL_Device.CONTENT_URI_DEVICES, values1, selection1,
						selectionArgs1);
			}
			// format message
			for (int i = 0; i < colorValue.length; i++) {
				int color = colorValue[i];
				int Blue = color % 256;
				color = color / 256;
				int Green = color % 256;
				color = color / 256;
				int Red = color % 256;
				rgbValue[3 * i] = Red;
				rgbValue[3 * i + 1] = Green;
				rgbValue[3 * i + 2] = Blue;
			}
			ControlRGB controlRGB = new ControlRGB(0, LumiHome.Uid,
					LumiHome.Session_id, rgbID, rgbValue, rgbStateID);

			// send to service
			sendMessageToService(NetMessage.CMD_APP_CONTROL_RGB, controlRGB);
			break;
		case OPT_SCENE_CREATE_SCENE:
			String sceneName = values.getAsString("Scene Name");
			int roomID = values.getAsInteger("Room ID");
			int hour = values.getAsInteger("hour");
			int minute = values.getAsInteger("minute");
			int mode = values.getAsInteger("Scene mode");

			int[] normalDevicesID = AbstractSceneActivity
					.convertStringToIntArray(values
							.getAsString("Normal Devices ID"));
			int[] normalDevicesState = AbstractSceneActivity
					.convertStringToIntArray(values
							.getAsString("Normal Devices State"));
			int[] RGBsID = AbstractSceneActivity.convertStringToIntArray(values
					.getAsString("RGBs ID"));
			int[] RGBsState = AbstractSceneActivity
					.convertStringToIntArray(values.getAsString("RGBs State"));
			if (normalDevicesID == null && RGBsID == null)
				return 0;
			int[] RGB = null;
			if (RGBsID != null) {
				RGB = new int[RGBsID.length * 3];
				for (int i = 0; i < RGBsID.length; i++) {
					int color = RGBsState[i];
					RGB[3 * i + 2] = color % 256;
					color = color / 256;
					RGB[3 * i + 1] = color % 256;
					color = color / 256;
					RGB[3 * i] = color % 256;
				}
			}
			CreateScene newScene = new CreateScene(0, LumiHome.Uid,
					LumiHome.Session_id, sceneName, roomID, mode, new Time(
							hour, minute), normalDevicesID, normalDevicesState,
					RGBsID, RGB);
			// send to service
			sendMessageToService(NetMessage.CMD_APP_CREATE_SCENE, newScene);
			break;

		case OPT_SCENE_EDIT_SCENE:
			Log.d(this.TAG, "Edit scene");
			String sceneName1 = values.getAsString("Scene name");
			int sceneID1 = values.getAsInteger("Scene ID");
			int scene_mode = values.getAsInteger("Scene mode");
			int scene_hour = values.getAsInteger("Hour");
			int scene_minute = values.getAsInteger("Minute");
			int room_id = values.getAsInteger("Room id");

			int[] unchangedNormalDevicesID = AbstractSceneActivity
					.convertStringToIntArray(values
							.getAsString("unchangedNormalDevicesID"));
			int[] unchangedNormalDevicesState = AbstractSceneActivity
					.convertStringToIntArray(values
							.getAsString("unchangedNormalDevicesState"));

			int[] unchangedRGBsID = AbstractSceneActivity
					.convertStringToIntArray(values
							.getAsString("unchangedRGBsID"));
			int[] unchangedRGBsState = AbstractSceneActivity
					.convertStringToIntArray(values
							.getAsString("unchangedRGBsState"));

			int[] changedNormalDevicesID = AbstractSceneActivity
					.convertStringToIntArray(values
							.getAsString("changedNormalDevicesID"));
			int[] changedNormalDevicesState = AbstractSceneActivity
					.convertStringToIntArray(values
							.getAsString("changedNormalDevicesState"));

			int[] changedRGBsID = AbstractSceneActivity
					.convertStringToIntArray(values
							.getAsString("changedRGBsID"));
			int[] changedRGBsState = AbstractSceneActivity
					.convertStringToIntArray(values
							.getAsString("changedRGBsState"));

			int[] newNormalDevicesID = AbstractSceneActivity
					.convertStringToIntArray(values
							.getAsString("newNormalDevicesID"));
			int[] newNormalDevicesState = AbstractSceneActivity
					.convertStringToIntArray(values
							.getAsString("newNormalDevicesState"));

			int[] newRGBsID = AbstractSceneActivity
					.convertStringToIntArray(values.getAsString("newRGBsID"));
			int[] newRGBsState = AbstractSceneActivity
					.convertStringToIntArray(values.getAsString("newRGBsState"));

			int[] deletedNormalDevicesID = AbstractSceneActivity
					.convertStringToIntArray(values
							.getAsString("deletedNormalDevicesID"));
			int[] deletedRGBsID = AbstractSceneActivity
					.convertStringToIntArray(values
							.getAsString("deletedRGBsID"));

			int[] unchangedRGB = null;
			if (unchangedRGBsID != null) {
				unchangedRGB = new int[unchangedRGBsID.length * 3];
				for (int i = 0; i < unchangedRGBsID.length; i++) {
					int color = unchangedRGBsState[i];
					unchangedRGB[3 * i + 2] = color % 256;
					color = color / 256;
					unchangedRGB[3 * i + 1] = color % 256;
					color = color / 256;
					unchangedRGB[3 * i] = color % 256;
				}
			}

			int[] changedRGB = null;
			if (changedRGBsID != null) {
				changedRGB = new int[changedRGBsID.length * 3];
				for (int i = 0; i < changedRGBsID.length; i++) {
					int color = changedRGBsState[i];
					changedRGB[3 * i + 2] = color % 256;
					color = color / 256;
					changedRGB[3 * i + 1] = color % 256;
					color = color / 256;
					changedRGB[3 * i] = color % 256;
				}
			}

			int[] newRGB = null;
			if (newRGBsID != null) {
				newRGB = new int[newRGBsID.length * 3];
				for (int i = 0; i < newRGBsID.length; i++) {
					int color = newRGBsState[i];
					newRGB[3 * i + 2] = color % 256;
					color = color / 256;
					newRGB[3 * i + 1] = color % 256;
					color = color / 256;
					newRGB[3 * i] = color % 256;
				}
			}

			// format message
			EditScene edtScene = new EditScene(0, LumiHome.Uid,
					LumiHome.Session_id, sceneName1, sceneID1, room_id,
					scene_mode, scene_hour, scene_minute,
					unchangedNormalDevicesID, unchangedNormalDevicesState,
					unchangedRGBsID, unchangedRGB, changedNormalDevicesID,
					changedNormalDevicesState, changedRGBsID, changedRGB,
					newNormalDevicesID, newNormalDevicesState, newRGBsID,
					newRGB, deletedNormalDevicesID, deletedRGBsID);
			// send to service
			sendMessageToService(NetMessage.CMD_APP_EDIT_SCENE, edtScene);
			break;
		case OPT_SCENE_TURNON_SCENE:
			int sceneID = values.getAsInteger(TBL_Scene._ID);
			TurnOnScene actScene = new TurnOnScene(0, LumiHome.Uid,
					LumiHome.Session_id, sceneID);
			// send to service
			sendMessageToService(NetMessage.CMD_APP_ACTIVATE_SCENE, actScene);
			break;
		case OPT_SCENE_TURNOFF_SCENE:
			break;
		case OPT_SCENE_DELETE_SCENE:
			int[] sceneIDs = EditSceneFragment.convertStringToIntArray(values
					.getAsString("Scene IDs"));
			DelScene delScene = new DelScene(0, LumiHome.Uid,
					LumiHome.Session_id, sceneIDs);
			// send to service
			sendMessageToService(NetMessage.CMD_APP_DEL_SCENE, delScene);
			break;
		case OPT_SCHEDULE:
			effect = sqLiteDatabase.update(DatabaseHelper.DB_TBL_SCHEDULE,
					values, selection, selectionArgs);
			break;
		case OPT_SCHEDULE_TURN_ON:
			int schedule_id = values.getAsInteger("scheduleId");
			ToggleSchedule toggleSchedule = new ToggleSchedule(0, LumiHome.Uid,
					LumiHome.Session_id, schedule_id,
					Schedule.SCHEDULE_STATE_ON);
			sendMessageToService(NetMessage.CMD_APP_TOGGLE_SCHEDULE,
					toggleSchedule);
			Log.d("ban tin", "OnturnOff");
			break;
		case OPT_SCHEDULE_TURN_OFF:
			int scheduleId = values.getAsInteger("scheduleId");
			ToggleSchedule toggleSchedule1 = new ToggleSchedule(0,
					LumiHome.Uid, LumiHome.Session_id, scheduleId,
					Schedule.SCHEDULE_STATE_OFF);
			sendMessageToService(NetMessage.CMD_APP_TOGGLE_SCHEDULE,
					toggleSchedule1);
			break;
		case OPT_SCHEDULE_ADD:
			boolean repeat = values.getAsBoolean("Repeat");
			int deviceId = values.getAsInteger("Device Id");

			boolean[] days = new boolean[7];
			days[0] = values.getAsBoolean("Monday");
			days[1] = values.getAsBoolean("Tuesday");
			days[2] = values.getAsBoolean("Wednesday");
			days[3] = values.getAsBoolean("Thursday");
			days[4] = values.getAsBoolean("Friday");
			days[5] = values.getAsBoolean("Saturday");
			days[6] = values.getAsBoolean("Sunday");
			
			int turnOnHour = values.getAsInteger("Turn on hour");
			int turnOnMinute = values.getAsInteger("Turn on minute");
			int turnOffHour = values.getAsInteger("Turn off hour");
			int turnOffMinute = values.getAsInteger("Turn off minute");
			int dev_state = values.getAsInteger("Dev_state");
			CreateSchedule createSchedule = new CreateSchedule(0, LumiHome.Uid,
					LumiHome.Session_id, 0, Schedule.SCHEDULE_STATE_ON,
					deviceId, repeat, days, new Time(turnOnHour, turnOnMinute),
					new Time(turnOffHour, turnOffMinute),
					new int[] { dev_state });
			sendMessageToService(NetMessage.CMD_APP_CREATE_SCHEDULE,
					createSchedule);
			break;
		case OPT_SCHEDULE_EDIT:
			boolean isNow_edit = values.getAsBoolean("isNow");
			boolean repeat1 = values.getAsBoolean("Repeat");
			int deviceId1 = values.getAsInteger("Device Id");
			int schedule_id_edit = values.getAsInteger("Schedule id");
			boolean[] days1 = new boolean[7];
			days1[0] = values.getAsBoolean("Monday");
			days1[1] = values.getAsBoolean("Tuesday");
			days1[2] = values.getAsBoolean("Wednesday");
			days1[3] = values.getAsBoolean("Thursday");
			days1[4] = values.getAsBoolean("Friday");
			days1[5] = values.getAsBoolean("Saturday");
			days1[6] = values.getAsBoolean("Sunday");
			int turnOnHour1 = values.getAsInteger("Turn on hour");
			int turnOnMinute1 = values.getAsInteger("Turn on minute");
			int turnOffMinute1 = values.getAsInteger("Turn off minute");
			int turnOffHour1 = values.getAsInteger("Turn off hour");
			int dev_state1 = values.getAsInteger("Dev_state");
			EditSchedule editSchedule = new EditSchedule(0, LumiHome.Uid,
					LumiHome.Session_id, schedule_id_edit,
					Schedule.SCHEDULE_STATE_ON, deviceId1, repeat1, days1,
					new Time(turnOnHour1, turnOnMinute1), new Time(
							turnOffHour1, turnOffMinute1),
					new int[] { dev_state1 }, isNow_edit);

			sendMessageToService(NetMessage.CMD_APP_EDIT_SCHEDULE, editSchedule);

			break;
		case OPT_SCHEDULE_DELETE:
			int schedule_ID = values.getAsInteger("Schedule id");
			int device_id = values.getAsInteger("device_id");
			DelSchedule delSchedule = new DelSchedule(0, LumiHome.Uid,
					LumiHome.Session_id, schedule_ID, device_id);
			sendMessageToService(NetMessage.CMD_APP_DEL_SCHEDULE, delSchedule);

			break;
		case OPT_END_APPLICATION:
			try {
				doUnbindService();
			} catch (Throwable t) {
				Log.e("CP", "Failed to unbind from the service", t);
			}
			break;

		}

		getContext().getContentResolver().notifyChange(uri, null);
		return effect;
	}

	public static int getDeviceStateIDByDeviceID(Context context, int DevID) {
		Uri uri = TBL_Device.CONTENT_URI_DEVICE_STATE_ID;
		String[] projection = new String[] { TBL_Device.STATE_ID };
		String selection = TBL_Device._ID + "=?";
		String[] selectionArgs = new String[] { DevID + "" };
		int deviceType = 0;
		Cursor cursor = context.getContentResolver().query(uri, projection,
				selection, selectionArgs, null);
		if (cursor != null) {
			if (cursor.moveToFirst())
				deviceType = cursor.getInt(cursor
						.getColumnIndex(TBL_Device.STATE_ID));
		} else
			deviceType = -1;
		return deviceType;
	}

	public static void insertDataStateFromHCToDB(Context context,
			ArrayList<Device> devices) {
		for (int k = 0; k < devices.size(); k++) {
			DeviceState deviceState = devices.get(k).getDeviceState();
			// get DeviceState id
			int DeviceStateID = getDeviceStateIDByDeviceID(context, devices
					.get(k).getId());
			// get DeviceState id//

			// insert DeviceState
			ContentValues contentValues = new ContentValues();
			contentValues.put(TBL_DeviceState.VALUE, deviceState.getValue());
			contentValues.put(TBL_DeviceState.RGB, deviceState.getRGB());
			contentValues.put(TBL_DeviceState.BLIND_STATE,
					deviceState.getBlind_state());
			contentValues.put(TBL_DeviceState.ID, DeviceStateID);
			context.getContentResolver().update(
					TBL_DeviceState.CONTENT_URI_DEVICE_STATE, contentValues,
					null, null);
			// int device_state_id=Integer.parseInt(uri.getLastPathSegment());
			contentValues.clear();
			// insert DeviceState//
		}
	}

	/**
	 * Insert Config receive from HC to Database
	 * 
	 * @param context
	 * @param floors
	 */
	public static void insertConfigFromHCToDB(Context context,
			ArrayList<Floor> floors) {

		// del existing data in db
		context.getContentResolver().delete(TBL_Floor.CONTENT_URI_FLOOR, null,
				null);
		context.getContentResolver().delete(TBL_Room.CONTENT_URI_ROOM, null,
				null);
		context.getContentResolver().delete(TBL_Device.CONTENT_URI_DEVICES,
				null, null);
		context.getContentResolver().delete(TBL_Scene.CONTENT_URI_SCENE, null,
				null);
		context.getContentResolver().delete(
				TBL_DeviceScene.CONTENT_URI_DEVICE_SCENE, null, null);
		context.getContentResolver().delete(
				TBL_DeviceState.CONTENT_URI_DEVICE_STATE, null, null);
		context.getContentResolver().delete(TBL_Schedule.CONTENT_URI_SCHEDULE,
				null, null);
		// del existing data in db//

		// insert new data
		for (int i = 0; i < floors.size(); i++) {
			Floor floor = floors.get(i);
			// insert floor
			ContentValues contentValues = new ContentValues();
			contentValues.put(TBL_Floor._ID, floor.getId());
			contentValues.put(TBL_Floor.NAME, floor.getName());
			context.getContentResolver().insert(TBL_Floor.CONTENT_URI_FLOOR,
					contentValues);
			contentValues.clear();
			// insert floor//

			ArrayList<Room> rooms = floor.getRooms();
			for (int j = 0; j < rooms.size(); j++) {
				Room room = rooms.get(j);
				// insert room
				contentValues.put(TBL_Room._ID, room.getId());
				contentValues.put(TBL_Room.FLOOR_ID, floor.getId());
				contentValues.put(TBL_Room.NAME, room.getName());
				context.getContentResolver().insert(TBL_Room.CONTENT_URI_ROOM,
						contentValues);
				contentValues.clear();
				// insert room//

				// insert devices
				ArrayList<Device> devices = room.getDevices();
				for (int k = 0; k < devices.size(); k++) {
					DeviceState deviceState = devices.get(k).getDeviceState();
					// insert DeviceState
					// Hieu them vao
					// contentValues.put(TBL_DeviceState._ID,
					// 0);
					// End
					contentValues.put(TBL_DeviceState.VALUE,
							deviceState.getValue());
					contentValues
							.put(TBL_DeviceState.RGB, deviceState.getRGB());
					contentValues.put(TBL_DeviceState.BLIND_STATE,
							deviceState.getBlind_state());
					Uri uri = context.getContentResolver().insert(
							TBL_DeviceState.CONTENT_URI_DEVICE_STATE,
							contentValues);
					int device_state_id = Integer.parseInt(uri
							.getLastPathSegment());
					contentValues.clear();
					// insert DeviceState//

					// insert Device
					Device device = devices.get(k);
					contentValues.put(TBL_Device._ID, device.getId());
					contentValues.put(TBL_Device.NAME, device.getName());
					contentValues.put(TBL_Device.ROOM_ID, room.getId());
					contentValues.put(TBL_Device.STATE_ID, device_state_id);
					contentValues.put(TBL_Device.TYPE_ID, device.getType_id());
					contentValues.put(TBL_Device.IS_CONTROL, 0);
					context.getContentResolver().insert(
							TBL_Device.CONTENT_URI_DEVICES, contentValues);
					contentValues.clear();
					// insert Device//

					// insert Schedule
					if (!device.isEmptySchedule()) {
						int count = device.getCountSchedule();
						for (int a = 0; a < count; a++) {
							Schedule schedule = device.getSchedule(a);
							// inset device_state
							DeviceState deviceStateSchedule = schedule
									.getDeviceState();

							contentValues.put(TBL_DeviceState.VALUE,
									deviceStateSchedule.getValue());
							contentValues.put(TBL_DeviceState.RGB,
									deviceStateSchedule.getRGB());
							contentValues.put(TBL_DeviceState.BLIND_STATE,
									deviceStateSchedule.getBlind_state());
							Uri uriSchedule = context
									.getContentResolver()
									.insert(TBL_DeviceState.CONTENT_URI_DEVICE_STATE,
											contentValues);
							int schedule_state_id = Integer
									.parseInt(uriSchedule.getLastPathSegment());
							contentValues.clear();

							// Author:Hieu inset Schedule
							contentValues.put(TBL_Schedule._ID,
									schedule.getId());
							contentValues.put(TBL_Schedule.DEVICE_ID,
									schedule.getDevice_id());
							contentValues.put(TBL_Schedule.STATE,
									schedule.getState());
							contentValues.put(TBL_Schedule.REPEAT,
									schedule.getRepeat());
							contentValues.put(TBL_Schedule.MONDAY,
									schedule.isMonday());
							contentValues.put(TBL_Schedule.TUESDAY,
									schedule.isTuesday());
							contentValues.put(TBL_Schedule.WEDNESDAY,
									schedule.isWednesday());
							contentValues.put(TBL_Schedule.THURSDAY,
									schedule.isThursday());
							contentValues.put(TBL_Schedule.FRIDAY,
									schedule.isFriday());
							contentValues.put(TBL_Schedule.SATURDAY,
									schedule.isSaturday());
							contentValues.put(TBL_Schedule.SUNDAY,
									schedule.isSunday());
							contentValues.put(TBL_Schedule.HOUR,
									schedule.getHour());
							contentValues.put(TBL_Schedule.MINUTE,
									schedule.getMinute());
							/*
							 * contentValues.put(TBL_Schedule.DURATION,
							 * schedule.getDuration());
							 */

							contentValues.put(TBL_Schedule.HOUR_END,
									schedule.getHour_end());
							contentValues.put(TBL_Schedule.MINUTE_END,
									schedule.getMinute_end());

							contentValues.put(TBL_Schedule.STATE_ID,
									schedule_state_id);
							context.getContentResolver().insert(
									TBL_Schedule.CONTENT_URI_SCHEDULE,
									contentValues);
							contentValues.clear();

						}
					}
					// end insert Schedule
				}

				// insert scenes
				ArrayList<Scene> scenes = room.getScenes();
				for (Scene scene : scenes) {
					int NumOfDevices = scene.getDevicesId().size();
					for (int l = 0; l < NumOfDevices; l++) {
						// insert device state
						contentValues.put(TBL_DeviceState.VALUE, scene
								.getDevicesState().get(l).getValue());
						contentValues.put(TBL_DeviceState.BLIND_STATE, scene
								.getDevicesState().get(l).getBlind_state());
						contentValues.put(TBL_DeviceState.RGB, scene
								.getDevicesState().get(l).getRGB());
						Uri uri = context.getContentResolver().insert(
								TBL_DeviceState.CONTENT_URI_DEVICE_STATE,
								contentValues);
						int device_state_id = Integer.parseInt(uri
								.getLastPathSegment());
						contentValues.clear();

						// insert scene device
						contentValues.put(TBL_DeviceScene.DEVICE_ID, scene
								.getDevicesId().get(l));
						contentValues.put(TBL_DeviceScene.SCENE_ID,
								scene.getId());
						contentValues.put(TBL_DeviceScene.STATE_ID,
								device_state_id);
						uri = context.getContentResolver().insert(
								TBL_DeviceScene.CONTENT_URI_DEVICE_SCENE,
								contentValues);
						contentValues.clear();
					}
					// insert scene
					contentValues.put(TBL_Scene._ID, scene.getId());
					contentValues.put(TBL_Scene.HOUR, scene.getTurnOnTime()
							.getHour());
					contentValues.put(TBL_Scene.MINUTE, scene.getTurnOnTime()
							.getMinute());
					contentValues.put(TBL_Scene.MODE, scene.getMode());
					contentValues.put(TBL_Scene.NAME, scene.getName());
					contentValues.put(TBL_Scene.ROOM_ID, scene.getRoom_id());
					contentValues.put(TBL_Scene.STATE, scene.getState());
					context.getContentResolver().insert(
							TBL_Scene.CONTENT_URI_SCENE, contentValues);
					contentValues.clear();
				}
			}
		}
	}

	public static int getStateLengthByType(int Type) {
		int result = -1;
		if (Type == Device.DEVICE_TYPE_LIGHT)
			result = 1;
		if (Type == Device.DEVICE_TYPE_DIMMER)
			result = 1;
		if (Type == Device.DEVICE_TYPE_VER_BLIND)
			result = 1;
		if (Type == Device.DEVICE_TYPE_HOR_BLIND)
			result = 1;
		if (Type == Device.DEVICE_TYPE_AIRCON)
			result = 1;
		if (Type == Device.DEVICE_TYPE_HEATER)
			result = 1;
		if (Type == Device.DEVICE_TYPE_RGB)
			result = 3;
		if (Type == Device.DEVICE_TYPE_FAN)
			result = 1;
		if (Type == Device.DEVICE_TYPE_PIR)
			result = 1;
		if (Type == Device.DEVICE_TYPE_ROLL_DOOR)
			result = 1;
		return result;
	}

	public static DeviceState getDeviceStateByType(int DeviceType, int[] State) {
		DeviceState devState = new DeviceState();
		if (DeviceType == Device.DEVICE_TYPE_HOR_BLIND
				|| DeviceType == Device.DEVICE_TYPE_VER_BLIND) { // blinds
			int value = State[0] % 16;
			if (value < Device.DEVICE_STATE_BLIND_MIN_LEVEL)
				devState.setValue(Device.DEVICE_STATE_BLIND_MIN_LEVEL);
			else if (value > Device.DEVICE_STATE_BLIND_MAX_LEVEL)
				devState.setValue(Device.DEVICE_STATE_BLIND_MAX_LEVEL);
			else
				devState.setValue(value);
			// devState.setBlind_state((State[0]-State[0]%16)/16);
			devState.setBlind_state(Device.DEVICE_STATE_BLIND_STATE_STOPPED);
		} else if (DeviceType == Device.DEVICE_TYPE_RGB) { // RGB
			devState.setRGB(256 * 256 * (State[0]) + 256 * (State[1])
					+ (State[2]));
		} else if (DeviceType == Device.DEVICE_TYPE_ROLL_DOOR) { // Cua cuon

		} else { // other: ON/OFF and dimmer
			devState.setValue(State[0]);
		}
		return devState;

	}

	// Get type of device with given ID
	public static int getType_id(Context context, int deviceID) {
		int deviceType = -1;
		Uri uri = TBL_Device.CONTENT_URI_DEVICE_TYPE;
		String[] projection = new String[] { TBL_Device.TYPE_ID };
		String selection = TBL_Device._ID + "=?";
		String[] selectionArgs = new String[] { deviceID + "" };

		Cursor cursor = context.getContentResolver().query(uri, projection,
				selection, selectionArgs, null);
		if (cursor != null) {
			if (cursor.moveToFirst())
				deviceType = cursor.getInt(cursor
						.getColumnIndex(TBL_Device.TYPE_ID));
		} else
			deviceType = -1;
		return deviceType;
	}

	public static int getStateLengthByID(Context context, int DevID) {
		int type = getType_id(context, DevID);
		if (type > 0)
			return getStateLengthByType(type);
		else
			return -1;
	}

	// Extract state of device with given ID from given int array
	public static DeviceState getDeviceStateByID(Context context, int DevID,
			int[] State) {
		return getDeviceStateByType(getType_id(context, DevID), State);
	}

	public static String getFloorName(int floor_id) {
		String FloorName = "";
		switch (floor_id) {
		case 0:
			FloorName = "Tầng hầm";
			break;
		default:
			FloorName = "Tầng " + floor_id;
		}
		return FloorName;
	}

	public static DeviceState getDeviceStateFromDB(Context context, int deviceID) {
		DeviceState deviceState = new DeviceState();
		Uri uri = TBL_DeviceState.CONTENT_URI_DEVICE_STATE;
		String selection = TBL_Device._ID + "=?";
		String[] selectionArgs = new String[] { deviceID + "" };
		Cursor cursor = context.getContentResolver().query(uri, null,
				selection, selectionArgs, null);
		if (cursor != null) {
			if (cursor.moveToFirst()) {
				deviceState.setRGB(cursor.getInt(cursor
						.getColumnIndex(TBL_DeviceState.RGB)));
				deviceState.setId(cursor.getInt(cursor
						.getColumnIndex(TBL_DeviceState._ID)));
				deviceState.setValue(cursor.getInt(cursor
						.getColumnIndex(TBL_DeviceState.VALUE)));
			}
		}
		return deviceState;
	}

	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
		mServiceMessenger = new Messenger(service);
		try {
			Message msg = Message.obtain(null,
					SmartHomeService.MSG_REGISTER_CLIENT);
			msg.replyTo = mMessenger;
			mServiceMessenger.send(msg);
		} catch (RemoteException e) {
			// In this case the service has crashed before we could even do
			// anything with it
		}
	}

	@Override
	public void onServiceDisconnected(ComponentName name) {
		// This is called when the connection with the service has been
		// unexpectedly disconnected - process crashed.
		mServiceMessenger = null;
		Log.d("CP", "onServiceDisconnected");
	}

	/**
	 * Send data to the service
	 * 
	 * @param intvaluetosend
	 *            The data to send
	 */
	private void sendMessageToService(int MsgType, AppMsg appMsg) {
		if (mIsBound) {
			if (mServiceMessenger != null) {
				try {
					Message msg = Message.obtain(null,
							SmartHomeService.UI2SER_NEW_MSG);
					Bundle b = new Bundle();
					b.putInt("Message Type", MsgType);
					b.putParcelable("ContentProvider Message", appMsg);
					msg.setData(b);
					msg.replyTo = mMessenger;
					mServiceMessenger.send(msg);
					Log.d("ContentProvider", "Send Msg to Service, MsgType = "
							+ MsgType);
				} catch (RemoteException e) {
				}
			}
		}
	}

	private void doUnbindService() {
		if (mIsBound) {
			// If we have received the service, and hence registered with it,
			// then now is the time to unregister.
			if (mServiceMessenger != null) {
				try {
					Message msg = Message.obtain(null,
							SmartHomeService.MSG_UNREGISTER_CLIENT);
					msg.replyTo = mMessenger;
					mServiceMessenger.send(msg);
				} catch (RemoteException e) {
					// There is nothing special we need to do if the service has
					// crashed.
				}
			}
			// Detach our existing connection.
			getContext().unbindService(mConnection);
			mIsBound = false;
			Log.d("CP", "Unbinding from Service");
		}
	}

	/**
	 * Handle incoming messages from MyService
	 */
	private class IncomingMessageHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			// Log.d(LOGTAG,"IncomingHandler:handleMessage");
			// switch (msg.what) {
			// case MyService.MSG_SET_INT_VALUE:
			// textIntValue.setText("Int Message: " + msg.arg1);
			// break;
			// case MyService.MSG_SET_STRING_VALUE:
			// String str1 = msg.getData().getString("str1");
			// textStrValue.setText("Str Message: " + str1);
			// break;
			// default:
			// super.handleMessage(msg);
			// }
		}
	}

}
